﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Data;
using Janus.BaseEntitys;
using Janus.Cores.Resources;
using Janus.Cores.Logger;
using Janus.Cores.Tools;
using Janus.Mes.Services.Interface;
using Janus.Mes.DTO;
using System.Linq.Expressions;
using Janus.Cores.Extension;

namespace Janus.Mes.WebClient
{
    public class BaseController : Controller
    {
        #region 服务
        /// <summary>
        /// 资产档案服务
        /// </summary>
        protected readonly static IAssets AssetsServices = ServiceFactory.Create<IAssets>();
        /// <summary>
        /// 工作日历服务
        /// </summary>
        protected readonly static ICalendar CalendarServices = ServiceFactory.Create<ICalendar>();
        /// <summary>
        /// 工作日历视图服务
        /// </summary>
        protected readonly static IVwCalendarSum VwCalendarSumServices = ServiceFactory.Create<IVwCalendarSum>();
        /// <summary>
        /// 检验地点服务
        /// </summary>
        protected readonly static ICheckAddress CheckAddressServices = ServiceFactory.Create<ICheckAddress>();
        /// <summary>
        /// 检验环境主表服务
        /// </summary>
        protected readonly static ICheckEnvH CheckEnvHServices = ServiceFactory.Create<ICheckEnvH>();
        /// <summary>
        /// 检验环境子表服务
        /// </summary>
        protected readonly static ICheckEnvS CheckEnvSServices = ServiceFactory.Create<ICheckEnvS>();
        /// <summary>
        /// 检验特性服务
        /// </summary>
        protected readonly static ICheckFeature CheckFeatureServices = ServiceFactory.Create<ICheckFeature>();
        /// <summary>
        /// 检验单(原因分析文件)服务
        /// </summary>
        protected readonly static ICheckListAnalFile CheckListAnalFileServices = ServiceFactory.Create<ICheckListAnalFile>();
        /// <summary>
        /// 检验单(原因分析)服务
        /// </summary>
        protected readonly static ICheckListAnalysis CheckListAnalysisServices = ServiceFactory.Create<ICheckListAnalysis>();
        /// <summary>
        /// 检验单子表(缺陷描述)服务
        /// </summary>
        protected readonly static ICheckListDefect CheckListDefectServices = ServiceFactory.Create<ICheckListDefect>();
        /// <summary>
        /// 检验单主表服务
        /// </summary>
        protected readonly static ICheckListH CheckListHServices = ServiceFactory.Create<ICheckListH>();
        /// <summary>
        /// 检验单(改善对策文件)服务
        /// </summary>
        protected readonly static ICheckListImprFile CheckListImprFileServices = ServiceFactory.Create<ICheckListImprFile>();
        /// <summary>
        /// 检验单子表(检验特性)服务
        /// </summary>
        protected readonly static ICheckListS CheckListSServices = ServiceFactory.Create<ICheckListS>();
        /// <summary>
        /// 检验单子表(责任判定表)服务
        /// </summary>
        protected readonly static ICheckListSRespH CheckListSRespHServices = ServiceFactory.Create<ICheckListSRespH>();
        /// <summary>
        /// 检验项目表服务
        /// </summary>
        protected readonly static ICheckProject CheckProjectServices = ServiceFactory.Create<ICheckProject>();
        /// <summary>
        /// 检验单(改善对策)服务
        /// </summary>
        protected readonly static IChekListImprove ChekListImproveServices = ServiceFactory.Create<IChekListImprove>();
        /// <summary>
        /// 计量单位服务
        /// </summary>
        protected readonly static IComputationUnit ComputationUnitServices = ServiceFactory.Create<IComputationUnit>();
        /// <summary>
        /// 工艺路线主表服务
        /// </summary>
        protected readonly static ICraftRouteH CraftRouteHServices = ServiceFactory.Create<ICraftRouteH>();
        /// <summary>
        /// 工艺路线资源清单表服务
        /// </summary>
        protected readonly static ICraftRouteList CraftRouteListServices = ServiceFactory.Create<ICraftRouteList>();
        /// <summary>
        /// 工艺路线子表(工序)服务
        /// </summary>
        protected readonly static ICraftRouteS CraftRouteSServices = ServiceFactory.Create<ICraftRouteS>();
        /// <summary>
        /// 客户档案服务
        /// </summary>
        protected readonly static ICustomer CustomerServices = ServiceFactory.Create<ICustomer>();
        /// <summary>
        /// 自定义抽样主表服务
        /// </summary>
        protected readonly static ICustomSampH CustomSampHServices = ServiceFactory.Create<ICustomSampH>();
        /// <summary>
        /// 自定义抽样参数明细表服务
        /// </summary>
        protected readonly static ICustomSampPara CustomSampParaServices = ServiceFactory.Create<ICustomSampPara>();
        /// <summary>
        /// 自定义抽样子表服务
        /// </summary>
        protected readonly static ICustomSampS CustomSampSServices = ServiceFactory.Create<ICustomSampS>();
        /// <summary>
        /// 数据字典主表服务
        /// </summary>
        protected readonly static IDataDicH DataDicHServices = ServiceFactory.Create<IDataDicH>();
        /// <summary>
        /// 数据字典子表服务
        /// </summary>
        protected readonly static IDataDicS DataDicSServices = ServiceFactory.Create<IDataDicS>();
        /// <summary>
        /// 缺陷分类主表服务
        /// </summary>
        protected readonly static IDefectCatH DefectCatHServices = ServiceFactory.Create<IDefectCatH>();
        /// <summary>
        /// 缺陷分类子表服务
        /// </summary>
        protected readonly static IDefectCatS DefectCatSServices = ServiceFactory.Create<IDefectCatS>();
        /// <summary>
        /// 缺陷等级服务
        /// </summary>
        protected readonly static IDefectLevel DefectLevelServices = ServiceFactory.Create<IDefectLevel>();
        /// <summary>
        /// 缺陷原因服务
        /// </summary>
        protected readonly static IDefectReason DefectReasonServices = ServiceFactory.Create<IDefectReason>();
        /// <summary>
        /// 员工档案服务
        /// </summary>
        protected readonly static IEmployee EmployeeServices = ServiceFactory.Create<IEmployee>();
        /// <summary>
        /// 环境项目主表服务
        /// </summary>
        protected readonly static IEnvProjectH EnvProjectHServices = ServiceFactory.Create<IEnvProjectH>();
        /// <summary>
        /// 环境项目子表(单位)服务
        /// </summary>
        protected readonly static IEnvProjectS EnvProjectSServices = ServiceFactory.Create<IEnvProjectS>();
        /// <summary>
        /// 设备类别组别表服务
        /// </summary>
        protected readonly static IEquiCatGroup EquiCatGroupServices = ServiceFactory.Create<IEquiCatGroup>();
        /// <summary>
        /// 设备类别主表服务
        /// </summary>
        protected readonly static IEquiCatH EquiCatHServices = ServiceFactory.Create<IEquiCatH>();
        /// <summary>
        /// 设备类别子表服务
        /// </summary>
        protected readonly static IEquiCatS EquiCatSServices = ServiceFactory.Create<IEquiCatS>();
        /// <summary>
        /// 设备档案主表服务
        /// </summary>
        protected readonly static IEquipmentH EquipmentHServices = ServiceFactory.Create<IEquipmentH>();
        /// <summary>
        /// 设备档案子表服务
        /// </summary>
        protected readonly static IEquipmentS EquipmentSServices = ServiceFactory.Create<IEquipmentS>();
        /// <summary>
        ///   服务
        /// </summary>
        protected readonly static IIndicator IndicatorServices = ServiceFactory.Create<IIndicator>();
        /// <summary>
        /// 物料信息服务
        /// </summary>
        protected readonly static IInventory InventoryServices = ServiceFactory.Create<IInventory>();
        /// <summary>
        /// 仓位档案服务
        /// </summary>
        protected readonly static ILocation LocationServices = ServiceFactory.Create<ILocation>();
        /// <summary>
        /// 保养项目服务
        /// </summary>
        protected readonly static IMaintainProject MaintainProjectServices = ServiceFactory.Create<IMaintainProject>();
        /// <summary>
        /// 管理清单服务
        /// </summary>
        protected readonly static IManagementList ManagementListServices = ServiceFactory.Create<IManagementList>();
        /// <summary>
        ///   服务
        /// </summary>
        protected readonly static IModule ModuleServices = ServiceFactory.Create<IModule>();
        /// <summary>
        /// 工单主表服务
        /// </summary>
        protected readonly static IMoOrderH MoOrderHServices = ServiceFactory.Create<IMoOrderH>();
        /// <summary>
        /// 工单工序表服务
        /// </summary>
        protected readonly static IMoOrderProcess MoOrderProcessServices = ServiceFactory.Create<IMoOrderProcess>();
        /// <summary>
        /// 工单子表服务
        /// </summary>
        protected readonly static IMoOrderS MoOrderSServices = ServiceFactory.Create<IMoOrderS>();
        /// <summary>
        /// 组织架构服务
        /// </summary>
        protected readonly static IOrganization OrganizationServices = ServiceFactory.Create<IOrganization>();
        /// <summary>
        /// 初中终物|巡检记录服务
        /// </summary>
        protected readonly static IPatrolRecord PatrolRecordServices = ServiceFactory.Create<IPatrolRecord>();
        /// <summary>
        /// 工序档案服务
        /// </summary>
        protected readonly static IProcess ProcessServices = ServiceFactory.Create<IProcess>();
        /// <summary>
        /// 工序检验方案明细服务
        /// </summary>
        protected readonly static IProcessCheckDetail ProcessCheckDetailServices = ServiceFactory.Create<IProcessCheckDetail>();
        /// <summary>
        /// 工序检验文档服务
        /// </summary>
        protected readonly static IProcessCheckFile ProcessCheckFileServices = ServiceFactory.Create<IProcessCheckFile>();
        /// <summary>
        /// 工序检验方案主表服务
        /// </summary>
        protected readonly static IProcessCheckH ProcessCheckHServices = ServiceFactory.Create<IProcessCheckH>();
        /// <summary>
        /// 工序检验方案子表服务
        /// </summary>
        protected readonly static IProcessCheckS ProcessCheckSServices = ServiceFactory.Create<IProcessCheckS>();
        /// <summary>
        /// 产品结构服务
        /// </summary>
        protected readonly static IProductBom ProductBomServices = ServiceFactory.Create<IProductBom>();
        /// <summary>
        /// 产品检验方案参考文件服务
        /// </summary>
        protected readonly static IProductCheckFile ProductCheckFileServices = ServiceFactory.Create<IProductCheckFile>();
        /// <summary>
        /// 产品检验方案主表服务
        /// </summary>
        protected readonly static IProductCheckH ProductCheckHServices = ServiceFactory.Create<IProductCheckH>();
        /// <summary>
        /// 产品检验方案子表服务
        /// </summary>
        protected readonly static IProductCheckS ProductCheckSServices = ServiceFactory.Create<IProductCheckS>();
        /// <summary>
        /// 品质参数服务
        /// </summary>
        protected readonly static IQCParameter QCParameterServices = ServiceFactory.Create<IQCParameter>();
        /// <summary>
        ///   服务
        /// </summary>
        protected readonly static IRolers RolersServices = ServiceFactory.Create<IRolers>();
        /// <summary>
        /// 采样过程服务
        /// </summary>
        protected readonly static ISampProcess SampProcessServices = ServiceFactory.Create<ISampProcess>();
        /// <summary>
        /// 班次管理主表服务
        /// </summary>
        protected readonly static IShiftH ShiftHServices = ServiceFactory.Create<IShiftH>();
        /// <summary>
        /// 班次管理子表服务
        /// </summary>
        protected readonly static IShiftS ShiftSServices = ServiceFactory.Create<IShiftS>();
        /// <summary>
        /// 留样单服务
        /// </summary>
        protected readonly static IStaySampList StaySampListServices = ServiceFactory.Create<IStaySampList>();
        /// <summary>
        ///   服务
        /// </summary>
        protected readonly static ISysConfig SysConfigServices = ServiceFactory.Create<ISysConfig>();
        /// <summary>
        ///   服务
        /// </summary>
        protected readonly static ISysDictionary SysDictionaryServices = ServiceFactory.Create<ISysDictionary>();
        /// <summary>
        /// 工艺档案服务
        /// </summary>
        protected readonly static ITechnology TechnologyServices = ServiceFactory.Create<ITechnology>();
        /// <summary>
        /// 厂商档案服务
        /// </summary>
        protected readonly static IVendor VendorServices = ServiceFactory.Create<IVendor>();
        /// <summary>
        /// 仓库档案服务
        /// </summary>
        protected readonly static IWarehouse WarehouseServices = ServiceFactory.Create<IWarehouse>();
        /// <summary>
        /// 工作中心服务
        /// </summary>
        protected readonly static IWorkCenter WorkCenterServices = ServiceFactory.Create<IWorkCenter>();
        /// <summary>
        /// 工作单元服务
        /// </summary>
        protected readonly static IWorkUnit WorkUnitServices = ServiceFactory.Create<IWorkUnit>();




        #endregion

        #region 变量
        private CurrentUserDTO currentUser = new CurrentUserDTO();
        protected int pageSize = HelperCommon.PageSize;
        protected string sort = "";
        protected string order = "";
        protected int pageNumber = 1;

        /// <summary>
        /// 列表视图
        /// </summary>
        protected string viewList = string.Empty;
        /// <summary>
        /// 创建或修改视图
        /// </summary>
        protected string viewCreate = string.Empty;

        protected string ajaxStr = string.Empty;
        /// <summary>
        /// navTab ID
        /// </summary>
        protected virtual string navTabId { get; set; }
        protected object AreaName { get; set; }
        protected object ControllerName { get; set; }
        protected object ActionName { get; set; }

        /// <summary>
        /// 当前执行请求会话上下文
        /// </summary>
        protected ActionExecutingContext FilterContext = null;

        private PaginationDTO _pagination = new PaginationDTO() { PageSize = HelperCommon.PageSize };
        protected PaginationDTO Pagination
        {
            get
            {
                return _pagination;
            }
            set
            {
                _pagination = value;
            }
        }

        public string OperateID
        {
            get { return Session["OperateID"] as string; }
            set { Session["OperateID"] = ViewData["OperateID"] = value; }
        }

        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        protected CurrentUserDTO CurentUser
        {
            get
            {
                //if (Session["CurentUser"] != null)
                //{
                //    currentUser = Session["CurentUser"] as CurrentUserDTO;
                //    if (string.IsNullOrEmpty(currentUser.UserCode))
                //    {
                //        Response.Redirect("/login");
                //    }
                //    //if (currentUser.UserCode == "admin")
                //    //{
                //    //    currentUser.Modules = HelperCommon.GetModulesFromXML();
                //    //}
                //}
                //else
                //{
                //    Response.Redirect("/login");
                //}
                if (Session["CurentUser"] != null)
                {
                    currentUser = Session["CurentUser"] as CurrentUserDTO;
                }
                else
                {
                    currentUser.Modules = HelperCommon.GetModulesFromXML();
                    Session["CurentUser"] = currentUser;
                }
                currentUser.UserCode = "admin";
                currentUser.UserName = "管理员";
                currentUser.DeptCode = "admin";
                return currentUser;
            }
            set
            {
                currentUser = value;
                Session["CurentUser"] = currentUser;
            }
        }
        protected string AjaxResultSucess
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 200, ResourcesManager.SaveSuccess, navTabId, "", "closeCurrent");
            }
        }
        protected string AjaxResultSucessNoForward
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 200, ResourcesManager.SaveSuccess, navTabId, "", "");
            }
        }
        protected string AjaxResultFail
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 300, ResourcesManager.SaveFail, navTabId, "", "");
            }
        }
        protected string AjaxDeleteSucess
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 200, ResourcesManager.DeleteSuccess, navTabId, "", "");
            }
        }
        protected string AjaxDeleteFail
        {
            get
            {
                return string.Format(HelperCommon.AJAXFORMAT, 300, ResourcesManager.DeleteFail, navTabId, "", "");
            }
        }
        protected string AjaxActionSucess(string showTips, string refreshID = null)
        {
            return string.Format(HelperCommon.AJAXFORMAT, 200, showTips, refreshID ?? navTabId, "", "");
        }
        protected string AjaxActionFail(string showTips, string refreshID = null)
        {
            return string.Format(HelperCommon.AJAXFORMAT, 300, showTips, refreshID ?? navTabId, "", "");
        }
        #endregion

        #region 构造
        static BaseController()
        {
            //缓存所有操作地址
            //var allmodules = HelperCommon.GetModulesFromXML();
            //EnyimCachor.Set("allmodules", allmodules);
        }
        public BaseController()
        {
            //ViewData["AllRoles"] = GetRolesFromXML();
        }
        #endregion

        #region 控制器事件
        [ValidateInput(false)]
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //SetUser();
            FilterContext = filterContext;
            //if (Session["CurentUser"] != null)
            //{
            //    CurentUser = Session["CurentUser"] as CurrentUserDTO;
            //    if (string.IsNullOrEmpty(CurentUser.UserCode))
            //    {
            //        new AdminAttribute().OnActionExecuting(filterContext);
            //    }
            //}
            //else
            //{
            //    new AdminAttribute().OnActionExecuting(filterContext);
            //}

            AreaName = filterContext.RouteData.DataTokens["area"];
            ControllerName = filterContext.RouteData.Values["controller"];
            ActionName = filterContext.RouteData.Values["action"];

            navTabId = string.Format("{0}_{1}", AreaName, ControllerName).ToLower();
            ViewData["CurrentController"] = navTabId;
            var routeOpID = filterContext.RouteData.Values.Where(c => c.Key == "OpID").FirstOrDefault();
            string opID = !string.IsNullOrEmpty(routeOpID.Key) ? routeOpID.Value.ToString() : Request["OpID"];
            OperateID = opID;
        }
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            #region 获取用户权限
            if (CurentUser != null && CurentUser.Modules != null)
            {
                string currentUrl = Request.FilePath;
                //var currentModule = CurentUser.RolesPurview.Where(c => c.ID == OperateID).FirstOrDefault();
                var currentButtons = CurentUser.Modules.Where(c => c.Parent == OperateID && c.Types == (int)GlobaEnum.ModuleTypes.按钮).OrderBy(c => c.Order).ToList();
                var currentTabs = CurentUser.Modules.Where(c => c.Parent == OperateID && c.Types == (int)GlobaEnum.ModuleTypes.选项卡).OrderBy(c => c.Order).ToList();
                var currentFuncs = CurentUser.Modules.Where(c => c.Parent == OperateID && c.Types == (int)GlobaEnum.ModuleTypes.功能点).OrderBy(c => c.Order).ToList();
                var currentOther = CurentUser.Modules.Where(c => c.Parent == OperateID && c.Types == (int)GlobaEnum.ModuleTypes.其它).OrderBy(c => c.Order).ToList();
                ViewData["CurrentPageButtons"] = currentButtons;
                ViewData["CurrentTabs"] = currentTabs;
                ViewData["CurrentPageFuncs"] = currentFuncs;
                ViewData["currentOther"] = currentOther;
            }
            #endregion

            ViewData["pageSize"] = pageSize;
        }
        protected void ExceptionHand(Exception e)
        {

#if DEBUG
            throw e;
#endif
            LogManager.Default.Error(e);
        }

        protected override void OnException(ExceptionContext errorContext)
        {
            //LogManager.Default.Error(errorContext.Exception);
            //ViewBag.Errors = errorContext.Exception.Message;
            //errorContext.Result = new RedirectResult(Url.Action("Error", "login"));
        }
        #endregion

        #region 方法
        /// <summary>
        /// 获取通用搜索参数
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="form"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        protected SearchEntity<TModel> SearchPara<TModel>(FormCollection form) where TModel : Entity, new()
        {
            SearchEntity<TModel> searcher = null;
            TModel t = new TModel();
            #region 初始化页面对象
            //设置页面大小
            if (!string.IsNullOrEmpty(Request["PageSize"]))
            {
                int psize = pageSize;
                if (int.TryParse(Request["pageNum"], out psize))
                {
                    Pagination.PageSize = psize;
                }
            }
            else
            { Pagination.PageSize = pageSize; }

            //设置当前页面 
            int currentIndex = 1;
            if (!string.IsNullOrEmpty(Request["pageNum"]))
            {
                int.TryParse(Request["pageNum"], out currentIndex);
            }
            Pagination.CurrentIndex = currentIndex;

            //设置是否需要重新计算总记录
            if (!string.IsNullOrEmpty(Request["RowCount"]))
            {
                int rowCount = 0;
                if (int.TryParse(Request["RowCount"], out rowCount))
                {
                    Pagination.RowCount = rowCount;
                }
            }
            #endregion

            if (form != null && form.Count > 0)
            {
                TryUpdateModel(t, form);
            }
            if (t == null)
            {
                t = new TModel();
            }
            else
            {
                //var objType = t.GetType();
                //if (Pagination != null)
                //{
                //    //在搜索参数加上分页
                //    objType.GetProperty("Pagination").SetValue(t, Pagination ?? new PaginationDTO(), null);
                //}
            }
            searcher = new SearchEntity<TModel>(null, Pagination ?? new PaginationDTO());
            searcher.Model = t;
            //当前用户信息
            searcher.CurrentUser = CurentUser;

            ViewData["SearchParma"] = t;
            return searcher;
        }

        /// <summary>
        /// Form转Model并加上当前用户信息
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="form"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        protected TModel SetModel<TModel>(FormCollection form) where TModel : Entity, new()
        {
            TModel t = new TModel();
            if (form != null && form.Count > 0)
            {
                TryUpdateModel(t, form);
            }
            if (t == null)
            {
                t = new TModel();
            }
            else
            {
                //当前用户信息
                if (t.Id.IsGuid())
                {//新增
                    t.Creator = string.IsNullOrEmpty(t.Creator) ? CurentUser.UserName : t.Creator;
                    t.CreatorCode = t.CreatorCode ?? CurentUser.UserCode;
                    t.CreateDate = DateTime.Now;
                    t.RowState = DataRowState.Added;
                    t.OperDept = currentUser.DeptCode;
                    //t.Timestamp=BitConverter.GetBytes(DateTime.Now.Ticks);
                }
                else
                {//修改
                    t.RowState = DataRowState.Modified;
                    t.Updater = CurentUser.UserName;
                    t.UpdaterCode = CurentUser.UserCode;
                    t.UpdateDate = DateTime.Now;
                    //t.Timestamp = BitConverter.GetBytes(DateTime.Now.Ticks);
                }
            }
            return t;
        }
        //protected T GetID<T>(T t) where T : Entity
        //{
        //    if (!string.IsNullOrEmpty(Request["_id"]))
        //    {
        //        t.Id = new ObjectId(Request["_id"]);
        //    }
        //    return t;
        //}

        /// <summary>
        /// 存放总页数
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="ts"></param>
        //protected void SetRowCount<TModel>(List<TModel> ts) where TModel : SearchParam
        //{
        //    if (ts != null && ts.Count > 0)
        //    {
        //        var firstModel = ts.FirstOrDefault();
        //        ViewData["RowCount"] = firstModel.RowCount;
        //    }
        //}

        /// <summary>
        /// 初始化对象具有操作者数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="isCreate"></param>
        /// <returns></returns>
        protected T InitModel<T>(T t) where T : Entity, new()
        {
            if (t == null)
            {
                t = new T();
            }
            if (!t.Id.IsGuid())
            {
                t.RowState = DataRowState.Added;
                t.Creator = CurentUser.UserName;
                t.CreatorCode = CurentUser.UserCode;
                t.CreateDate = DateTime.Now;
                t.OperDept = currentUser.DeptCode;
            }
            t.Updater = CurentUser.UserName;
            t.UpdaterCode = CurentUser.UserCode;
            t.UpdateDate = DateTime.Now;
            //t.Timestamp = BitConverter.GetBytes(DateTime.Now.Ticks);
            return t;
        }

        /// <summary>
        /// 分页获取集合，默认按照创建时间倒序排列
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <typeparam name="TService">服务类型</typeparam>
        /// <param name="collection">表单数据</param>
        /// <param name="isForControl">是否数据制控权</param>
        /// <returns></returns>
        public virtual ResponseResult<IList<T>> FindAllDesc<T>(SearchEntity<T> searchParma, IBase<T> services, bool isAdmin = false)
            where T : BaseDTO, new()
        {
            searchParma.IsAdmin = isAdmin;
            //设置排序规则
            searchParma.Queriers.OrderDescBy<T>(c => c.UpdateDate);
            var result = services.FindAll(searchParma);
            if (result != null && !result.ErrorMessage.IsNotEmpty())
            {
                //设置分页总数
                ViewData["RowCount"] = result.Pagination.RowCount;
            }
            return result;
        }

        /// <summary>
        /// 分页获取集合
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <typeparam name="TService">服务类型</typeparam>
        /// <param name="collection">表单数据</param>
        /// <param name="isForControl">是否数据制控权</param>
        /// <returns></returns>
        public virtual ResponseResult<IList<T>> FindAll<T>(SearchEntity<T> searchParma, IBase<T> services, bool isAdmin = false)
           where T : BaseDTO, new()
        {
            searchParma.IsAdmin = isAdmin;
            var result = services.FindAll(searchParma);
            if (result != null && !result.ErrorMessage.IsNotEmpty())
            {
                //设置分页总数
                ViewData["RowCount"] = result.Pagination.RowCount;
            }
            return result;
        }

        #endregion

        #region Test Code
        private void SetUser()
        {
            if (Session["curentuser"] == null)
            {
                string userName = "Ben";
                if (Request.Cookies["user"] != null)
                {
                    userName = Request.Cookies["user"].Value;
                }
                //var model = employeService.GetEmployesByName("admin");// new Employes();

                //model.UserCode = "admin";
                //model.IsAdmin = true;
                //model.UserName = "Ben";
                // currentUser.UserInfo = model;
                currentUser.Modules = HelperCommon.GetModulesFromXML();
            }
            else
            {
                //获取菜单XML信息
                currentUser.Modules = HelperCommon.GetModulesFromXML();
            }
            Session["CurentUser"] = currentUser;
        }
        #endregion

    }
}